do "E:\yungyu\lottery_baby\do\set_environment.do"

clear
set more off

global control1 "i.pers_gender i.houhld_resid_cd pers_income_pre1 pers_asset_pre1 pers_earnings_pre1 pers_labor_pre1 married_pre1"
global control2 "totbaby_pre1"
global control3 "pre*redeem*"

use "$wdata\project_lottery_fertility_b3a6_first_5k.dta", clear
	
drop if prize10M > 5
	
gen tot_asset = pers_asset + spouse_asset
gen tot_rlest = pers_rlest + spouse_rlest

foreach var in rlest{
	gen v1 = pers_`var' if norm == -1
	egen pers_`var'_pre1 = mean(v1), by(houseid)
	drop v1
	gen v1 = tot_`var' if norm == -1
	egen tot_`var'_pre1 = mean(v1), by(houseid)
	drop v1
}

foreach var in saving liquidasset rlest{
	gen positive_`var'_pre1 = pers_`var'_pre1 > 0
}
gen positive_totrlest_pre1 = tot_rlest_pre1 > 0


replace norm_year = norm_year + 3		

cap rm "$table/temp/Tab4.txt"
cap rm "$table/temp/Tab4.xls"

foreach y in totbaby {
	foreach grp in saving liquidasset rlest{
		forv j = 0(1)1{
			
			sum `y' if current == 0 & norm == 2 & positive_`grp'_pre1 == `j'
			loc m0 = r(mean)
			sum `y' if current == 0 & norm == 9 & positive_`grp'_pre1 == `j'
			loc m1 = r(mean)
			loc bt = `m1' - `m0'
			loc bt: dis %9.3f `bt'
			
			sum tot_asset if current == 0 & norm == 2 & positive_`grp'_pre1 == `j'
			loc m0t = r(mean)
			sum tot_asset if current == 0 & norm == 9 & positive_`grp'_pre1 == `j'
			loc m1t = r(mean)
			loc bt_wt = `m1t' - `m0t' //Baseline trend in wealth
			loc m0t: dis %9.3f `m0t'
			loc bt_wt: dis %9.3f `bt_wt'
		
			reghdfe `y' currentxprizexp* prize10M c.prize10M#i.norm c.prize10M#1.current $control1 $control2 $control3 if positive_`grp'_pre1 == `j', a(norm#current year age) cl(houseid)
			
			outreg2 using "$table/temp/Tab4.xls" , append bd(3) sd(3) nocon keep(currentxprize*) ctitle(`grp'`j') addtext(Baseline Trend, `bt', Baseline Wealth, `m0t', Baseline Trend in Wealth, `bt_wt')
		}
	}
}

import delimited using "$table/temp/Tab4.txt", clear

forv i = 2(1)7{
    replace v`i' = "" in 2
}

replace v2 = "Deposit" in 2
replace v4 = "Liquid Asset" in 2
replace v6 = "Real Estate" in 2

foreach x in 2 4 6{
    replace v`x' = "0" in 3
}
foreach x in 3 5 7{
    replace v`x' = ">0" in 3
}

merge 1:1 _n using "$table/temp/Tab4-I.dta"
drop _m

order v1 v2 v3 vv2 v4 v5 vv3 v6 v7 vv4

forv i = 2(1)6{
	replace vv`i' = "Difference" in 3
}

drop vv1

export excel "$table/Tables.xlsx", sheet("Tab4") sheetreplace
